import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/userStore.js'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // ================ 登录端 ===============
    {
      path: '/login',
      name: 'login',
      component: () => import("@/views/Access/Login/index.vue")
    },
    {
      path: '/register',
      name: 'register',
      component: () => import("@/views/Access/Register/index.vue")
    },
    {
      path: '/introduction',
      name: 'introduction',
      component: () => import("@/views/Access/Introduction/index.vue")
    },
    {
      path: '/phonetics/test',
      name: 'phonetics-test',
      component: () => import("@/views/test/Phonetics/PronounceTest.vue")
    },

    // =================== 用户端 ==================
    {
      path: '/',
      component: () => import("@/views/user/Layout/index.vue"),
      children: [
        {
          path: '',
          name: 'home',
          component: () => import("@/views/user/home/index.vue")
        },
        {
          path: 'dictionary',
          name: 'dictionary',
          component: () => import("@/views/user/home/index.vue")
        },
        {
          path: 'ai-chat',
          name: 'ai-chat',
          component: () => import("@/views/user/AIChat/index.vue")
        },
        {
          path: 'exam',
          name: 'exam',
          component: () => import("@/views/user/home/index.vue")
        },
        {
          path: 'translation',
          name: 'translation',
          component: () => import("@/views/user/Translation/index.vue")
        }
      ]
    },

    // =================== 404 页面 ==================
    {
      path: '/404',
      name: '404',
      component: () => import("@/views/404/index.vue")
    },

    // 捕获所有未匹配的路由
    {
      path: '/:pathMatch(.*)*',
      redirect: '/404'
    }
  ],
})

// 路由守卫 - 处理未登录用户的访问控制
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 定义公开路由（不需要登录即可访问）
  const publicRoutes = ['/login', '/register', '/introduction']
  
  // 判断是否为公开路由
  const isPublicRoute = publicRoutes.includes(to.path)
  
  // 判断用户是否已登录（根据 access_token 或 userInfo）
  // const isLoggedIn = !!(userStore.userInfo?.access_token || userStore.userInfo?.username)
  const isLoggedIn = userStore.isLoggedIn

  if (isPublicRoute) {
    // 公开路由，直接放行
    next()
  } else if (isLoggedIn) {
    // 已登录用户访问受保护的路由，放行
    next()
  } else {
    // 未登录用户访问受保护的路由，跳转到登录页
    console.log('未登录，跳转到登录页')
    next('/login')
  }
})

export default router
